package com.bridgeintelligent.tag.webserver.schedule.service.imp;

import com.bridgeintelligent.tag.customer.entity.CustomersPage;
import com.bridgeintelligent.tag.customer.pojo.Customers;
import com.bridgeintelligent.tag.customer.service.CustomersService;
import com.bridgeintelligent.tag.webserver.engine.relyon.service.utils.EngineQueryApiUtils;
import com.bridgeintelligent.tag.webserver.schedule.api.ICustomerAmountService;
import com.bridgeintelligent.tag.webserver.schedule.api.page.HandlePage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description
 * @author: grp 2020-07-24 10:59
 **/
@Service
@AllArgsConstructor
@Slf4j
public class CustomerAmountService implements ICustomerAmountService {

    private CustomersService customersService;
    private EngineQueryApiUtils queryApiUtils;
    private ObjectMapper objectMapper;

    @Override
    public HandlePage updateByPage(int page, int size) {
        CustomersPage<Customers> customersPage = customersService.getDeployAndSeedCustomersByPage(page, size);
        List<Customers> content = customersPage.getContent();
        if(!CollectionUtils.isEmpty(content)){
            content.forEach(customers -> {
                updateAmount(customers);
            });
        }
        return HandlePage.builder().page(customersPage.getRequestPager()).totalPage(customersPage.getTotalPages()).message("success").finish(customersPage.getTotalPages()<=page).build();
    }

    private void updateAmount(Customers customers) {
        try{
            Customers info = customersService.findOneById(customers.getCustomersId());
            customers.setIndexId(info.getIndexId());
            customers.setDateType(info.getDateType());
            customersService.getCountAmount(customers, info.getQueryModel());
            if(customers.getCustomerAmount()==null){
                return;
            }
            customersService.update(customers);
        }catch (Exception e){
            log.error(customers.getCustomersId()+"更新客群人数出错", e);
        }
    }
}
